//
//  ViewController.swift
//  ExampleApp
//
//  Created by mac on 2025/3/8.
//

import UIKit
import RxCocoa
import RxSwift
import SnapKit
import Loaf
import CoreBluetooth


class ViewController: UIViewController {
    
    private lazy var disposeBag = DisposeBag()
    private let bluetoothManager = XCBluetoothManager.instance
    override func viewDidLoad() {
        
        super.viewDidLoad()
        addView()
        
        let bluetoothStateObservable = bluetoothManager.bluetoothStateObservable
        
        bluetoothStateObservable
            .map { $0 == .poweredOn }
            .distinctUntilChanged()
            .observe(on: MainScheduler.instance)
            .subscribe(onNext: { [weak self] isPoweredOn in
                guard let self = self else { return }
                autoConnectButton.setTitle(isPoweredOn ? "自动重连" : "打开蓝牙", for: .normal)
            })
            .disposed(by: disposeBag)
        
        autoConnectButton.rx.tap
            .withLatestFrom(bluetoothStateObservable)
            .flatMapLatest { state -> Observable<ConnectionState> in
                if state == .poweredOn {
                    return XCReconnectManager.instance.autoReconnectLastPeripheral()
                } else {
                    if let url = URL(string: UIApplication.openSettingsURLString),
                       UIApplication.shared.canOpenURL(url) {
                        UIApplication.shared.open(url, options: [:], completionHandler: nil)
                    }
                    return Observable.empty()
                }
            }
            .observe(on: MainScheduler.instance)
            .subscribe(onNext: {[weak self] connectionstate  in
                guard let self = self else { return }
                self.handleConnectionState(connectionstate)
            })
            .disposed(by: disposeBag)
        
        pushButton.rx.tap
            .observe(on: MainScheduler.instance)
            .subscribe(onNext: {
                let vc = RxBluetoothVC()
                vc.hidesBottomBarWhenPushed = true
                self.navigationController?.pushViewController(vc, animated: false)
            })
            .disposed(by: disposeBag)
        
        
    }
    
    lazy var pushButton = {
        let button = UIButton(type: .custom)
        button.backgroundColor = .orange
        button.setTitle("跳转页面", for: .normal)
        button.setTitleColor(.red, for: .normal)
        return button
    }()
    
    lazy var autoConnectButton = {
        let button = UIButton(type: .custom)
        button.backgroundColor = .orange
        button.setTitle("自动重连", for: .normal)
        button.setTitleColor(.red, for: .normal)
        return button
    }()
    
}

extension ViewController {
    
    // 处理连接状态的更新
    func handleConnectionState(_ connectState: ConnectionState) {
        switch connectState {
        case .connecting:
            showBluetoothMessage("蓝牙开始连接1", state: .success)
        case .connected:
            self.showBluetoothMessage("蓝牙连接成功1", state: .success)
            pushMsgVC()
            
        case .disconnected:
            self.showBluetoothMessage("蓝牙断开连接1", state: .warning)
        case .failed(let error):
            self.showBluetoothMessage("蓝牙连接错误1 -> \(error.localizedDescription)", state: .error)
            handleBluetoothError(error)
        }
    }
    
    func showBluetoothMessage(_ message: String, state: Loaf.State) {
        Loaf(message, state: state, sender: self).show()
    }
    
    func handleBluetoothError(_ error: Error) {
        if let error = error as NSError? {
            switch error.code {
            case CBError.connectionTimeout.rawValue:
                print("设备远离了导致的断开")
            case CBError.peripheralDisconnected.rawValue:
                print("设备主动断开导致的断开")
            default:
                print("断开失败 error == \(error)")
            }
        }
    }
    
    
    func addView() {
        
        self.view.backgroundColor = .white
        self.view.addSubview(pushButton)
        pushButton.snp.makeConstraints { make in
            make.center.equalToSuperview()
            make.size.equalTo(CGSize(width: 100, height: 50))
        }
        
        self.view.addSubview(autoConnectButton)
        autoConnectButton.snp.makeConstraints { make in
            make.top.equalTo(164)
            make.centerX.equalToSuperview()
            make.size.equalTo(CGSize(width: 100, height: 50))
        }
    }
    
    func pushMsgVC() {
        let vc = RXMessageVC()
        vc.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(vc, animated: false)
        
    }
    
}

